/*
 * Copyright (C) 2022 xuexiangjys(xuexiangjys@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package cn.kcrx.autoweightapp.utils

import android.util.Log
import ch.qos.logback.classic.LoggerContext
import ch.qos.logback.classic.joran.JoranConfigurator
import com.xuexiang.xaop.annotation.Permission
import com.xuexiang.xaop.consts.PermissionConsts
import org.slf4j.LoggerFactory
import java.io.ByteArrayInputStream

object LogUtil {


    val LOGCONFIG="""
        <configuration>
    <property name="LOG_HOME" value="/sdcard/kcrx/logs/" />
    <appender name="logcat" class="ch.qos.logback.classic.android.LogcatAppender">
        <tagEncoder>
            <pattern>kcrxlog</pattern>
        </tagEncoder>
        <encoder>
            <pattern>[%logger{12}]-[%thread]-%msg</pattern>
        </encoder>
    </appender>

    <!-- 按照每天生成日志文件 -->
    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!--日志文件输出的文件名-->
            <FileNamePattern>/sdcard/kcrx/logs/%d{yyyy-MM-dd}.log</FileNamePattern>
            <!--日志文件保留天数-->
            <MaxHistory>30</MaxHistory>
        </rollingPolicy>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <!--格式化输出：%d表示日期，%thread表示线程名，%-5level：级别从左显示5个字符宽度%msg：日志消息，%n是换行符-->
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{12} - %msg%n</pattern>
            <charset>UTF-8</charset>
        </encoder>
        <!--日志文件最大的大小-->
        <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
            <MaxFileSize>10MB</MaxFileSize>
        </triggeringPolicy>
    </appender>

    <root level="INFO">
        <appender-ref ref="logcat" />
        <appender-ref ref="FILE"/>
    </root>
</configuration>
    """

    fun configLog(){
        val  lc=LoggerFactory.getILoggerFactory() as LoggerContext
        lc.stop()
        val config= JoranConfigurator()
        config.context=lc
        try{
            Log.e("loginit","正在初始化日志配置!")
            config.doConfigure(ByteArrayInputStream(LOGCONFIG.toByteArray()))
        }catch (e:Exception){
            Log.e("loginit","初始化日志配置失败！",e)
            e.printStackTrace()
        }
    }
}